package cn.tiga.filters;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;



@Component // 必须交给spring管理，否则不能生效
public class LoginCheckFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //得到上下文对象
        RequestContext context = RequestContext.getCurrentContext();
        //得到当前请求url
        String uri = context.getRequest().getRequestURI();
        //判断是否包含lofin/register
        if (StringUtils.endsWithIgnoreCase(uri,"login") || StringUtils.endsWithIgnoreCase(uri,"register")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 得到token
        String token = RequestContext.getCurrentContext().getRequest().getHeader("token");
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        // 设置数据相应格式和编码
        response.setContentType(("application/json;charset=utf-8"));
        // 判断token是否为null
        if (StringUtils.isEmpty(token)){
            try {
                // 1.设置响应内容
                PrintWriter writer = response.getWriter();
                HashMap<String, Object> map = new HashMap<>();
                map.put("success", false);
                map.put("message", "登录校验失败，请重新登录！");
                String data = JSON.toJSONString(map);
                writer.write(data);
                // 2.阻止后续filter执行
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 如果要放行，这里返回null即可，不用管
        return null;
    }
}